<!--
 * @Description: 
 * @Version: 2.0
 * @Autor: snzo.chen
 * @Date: 2023-11-16 15:01:18
 * @LastEditors: snzo.chen
 * @LastEditTime: 2023-12-20 16:30:23
-->
<template>
  <ActionTable @addRow="showModal('ADD', { state: 0, packageType: 1 })" />
  <a-table :columns="columns" :row-key="(record) => record.id" :data-source="packageOfData" :pagination="false"
    :loading="state.loading" @change="handleTableChange">
    <template #bodyCell="{ column, record }">
      <template v-if="column.key === 'state'">
        <a-switch :checked="record.state === 1" checked-children="开启" un-checked-children="关闭"
          @click="(checked) => showMenu(checked, record)" />
      </template>
      <template v-if="column.key === 'action'">
        <TableRowAction :showSelect="false" @updateItem="showModal('UPDATE', record)" @deleteItem="delRow(record.id)">
          <a-button type="primary" @click="showPackageDay(record.id)">库存</a-button>
        </TableRowAction>
      </template>
    </template>
  </a-table>
  <contextHolder />
</template>
<script lang="ts" setup>
import {
  deleteTicketPackage,
  insertTicketPackage,
  selectPackageByExample,
  updateTicketPackage,
} from "@/api/ticket/package";
import { TableProps, message as $message, Modal } from "ant-design-vue";
import { h, onMounted, reactive, ref, watch } from "vue";
import { useRoute } from "vue-router";
import { router } from "@/router";
import { paginationToQuery } from "@/utils/common";
import TicketPackageItem from "./ticket-package-item.vue";
import { modalTitleEnum } from "@/enums/modalEnum";
const route = useRoute();
const [modal, contextHolder] = Modal.useModal();
const childRef = ref();

const sharedOnCell = (_, index) => {
  if (index === 0) {
    return { rowSpan: 10 };
  }
  if (index > 0) {
    return { rowSpan: 0 };
  }
};

const columns = [
  {
    dataIndex: "menuItemId",
    title: "归属ID",
    key: "menuItemId",
    align: "center",
    customCell: sharedOnCell,
  },
  {
    dataIndex: "id",
    title: "ID",
    key: "id",
    align: "center",
  },
  {
    dataIndex: "packageName",
    title: "商品名称",
    key: "packageName",
    align: "center",
  },
  {
    dataIndex: "price",
    title: "商品单价（元）",
    key: "price",
    align: "center",
  },
  {
    dataIndex: "totalPrice",
    title: "商品总价（元）",
    key: "totalPrice",
    align: "center",
  },
  {
    dataIndex: "stockNum",
    title: "售出数量",
    key: "stockNum",
    align: "center",
  },
  {
    dataIndex: "state",
    title: "状态",
    key: "state",
    align: "center",
  },
  {
    title: "操作",
    key: "action",
    align: "center",
  },
];
let menuItemId = 0;
let menuId = 0;
const packageOfData = ref<API.PackageItem[]>([]);
const state = reactive({
  loading: true,
  pagination: {
    pageSize: 10,
    current: 1,
    total: 0,
  },
});

watch(
  () => route.query.type,
  (newVal, oldVal) => {
    if (newVal === oldVal) return;
    loadData();
  }
);

/**
 * 获取数据
 */
const loadData = async () => {
  const { seachList, seachTotal } = await selectPackageByExample(
    { menuItemId },
    paginationToQuery(state.pagination)
  );
  packageOfData.value = seachList;
  state.pagination.total = seachTotal;

  state.loading = false;
};

/**
 * 分页切换
 * @param page
 */
const handleTableChange: TableProps["onChange"] = (page) => {
  state.pagination.current = page.current!;
  loadData();
};

/**
 * 查看库存
 * @param ticketPackageId
 */
const showPackageDay = (ticketPackageId: number) => {
  router.push({
    name: "ticket-package-day",
    params: { ticketMenu: menuItemId, ticketPackageId },
  });
};

/**
 * 查看二级类别
 */
// const subMenu = (menu) => {
//   router.push({ name: 'ticket-menu-item', query: { menuId: menu.id } });
// }

/**
 * 显示模态框
 * @param type
 * @param data
 */
const showModal = (type: string, data?: any) => {
  const menuForm = () =>
    h(TicketPackageItem, { ref: childRef, actionType: type, formData: data, menuId, menuItemId });
  modal.confirm({
    title: modalTitleEnum[type] + "商品",
    width: 1000,
    icon: null,
    content: menuForm,
    okText: "提交",
    cancelText: "取消",
    async onOk() {
      const params: API.PackageItem = childRef.value.formState;
      if (type === "ADD") {
        const { msg } = await insertTicketPackage(params);
        msg === "success" ? loadData() : $message.error(msg);
      } else if (type === "UPDATE") {
        const { msg } = await updateTicketPackage(params);
        msg === "success" ? loadData() : $message.error(msg);
      }
    },
    onCancel() {
      Modal.destroyAll();
    },
  });
};

/**
 * 删除商品
 */
const delRow = async (id) => {
  const { msg } = await deleteTicketPackage({ id });
  msg === "success" ? $message.success("删除成功") : $message.error(msg);
  loadData();
};

const showMenu = async (checked, packageItem) => {
  const { msg } = await updateTicketPackage({
    id: packageItem.id,
    state: checked ? 1 : 0,
  });
  msg === "success"
    ? (packageItem.state = Math.abs(packageItem.state - 1))
    : $message.error(msg);
  checked ? (packageItem.state = 1) : (packageItem.state = 0);
};

onMounted(() => {
  menuItemId = Number(route.params.menuItemId);
  menuId = Number(route.params.menuId);
  loadData();
});
</script>
<style lang="less" scoped>
.action-row {
  button {
    margin-left: 10px;

    &:first-child {
      margin-left: 0;
    }
  }
}
</style>
